package chapter2;

/**
 * 删除链表的中间节点和a/b处的节点
 */
public class RemoveNode {
    /**
     * 删除链表的中间节点，使用两个指针，一个走一步，一个走两步
     * @param head
     * @return
     */
    public ListNode removeMidNode(ListNode head) {
        if (head == null || head.next == null) return head;
        if (head.next.next == null) return head.next;
        ListNode pre = head;
        ListNode current = head.next.next;
        while (current.next != null && current.next.next !=null) {
            pre = pre.next;
            current = current.next.next;
        }
        pre.next = pre.next.next;
        return head;
    }

    /**
     * 删除链表a/b处的节点，要先遍历一边链表，统计节点的个数
     * 删除的节点位置为 a*n/b向上取整
     * @param head
     * @param a
     * @param b
     * @return
     */
    public ListNode removeByRadio(ListNode head, int a, int b) {
        if (a < 1 || a > b) {
            return head;
        }
        int n = 0;
        ListNode current = head;
        while (current != null) {
            n++;
            current = current.next;
        }
        // 向上取整,n为要删除的位置
        n = (int) Math.ceil((double) (a * n) / (double) b);
        if (n == 1) {
            head = head.next;
        }
        if (n > 1) {
            current = head;
            // 找到要删除节点的前一个位置
            while (--n != 1) {
                current = current.next;
            }
            current.next = current.next.next;
        }
        return head;
    }
}
